package Server.Common;

import Server.Cache.PlayerCache;

import java.util.ArrayList;
import java.util.List;

public class Scene extends Organization{
    private final AOINode head;
    private final AOINode tail;
    //public static List<Long> list;

    public Scene(){
        head = new AOINode(0,0,0);
        tail = new AOINode(0,0,0);
        head.xNext=tail;
        head.yNext=tail;
        tail.xPrev=head;
        tail.yPrev=head;
        System.out.println("scene id OK");
    }

    @Override
    public void addMember(Player player){
        AOINode node =new AOINode(player.getId(),player.getX(),player.getY());
        AOINode p = head.xNext;
        while(p!=null){
            if(p.x>node.x||p==tail){
                node.xNext=p;
                node.xPrev=p.xPrev;
                p.xPrev.xNext=node;
                p.xPrev=node;
                break;
            }
            p=p.xNext;
        }
        p=head.yNext;
        while(p!=null){
            if(p.y>node.y||p==tail){
                node.yNext=p;
                node.yPrev=p.yPrev;
                p.yPrev.yNext=node;
                p.yPrev=node;
                break;
            }
            p=p.yNext;
        }
    }

    @Override
    public void removeMember(Player player){
        AOINode node =getNode(player.getId());
        node.xPrev.xNext=node.xNext;
        node.xNext.xPrev=node.xPrev;
        node.yPrev.yNext=node.yNext;
        node.yNext.yPrev=node.yPrev;

        node.xPrev=null;
        node.yNext=null;
        node.yPrev=null;
        node.xNext=null;
    }

    @Override
    public List<Player> getList(Long id){
        AOINode node = getNode(id);
        list =getAOI(node,5,5);
        return list;
    }

    public AOINode getNode(Long key){
        AOINode p = head.xNext;
        while(p.xNext!=tail){
            if(key.equals(p.key)){
                break;
            }
            p = p.xNext;
        }
        return p;
    }


    public List<Player> getAOI(AOINode node,int x_dis,int y_dis){
        list=new ArrayList<>();
        list.add(PlayerCache.getInstance().getPlayer(node.key));
        AOINode cur = node.xNext;
        while(cur!=tail){
            if(cur.x-node.x > x_dis) {
                break;
            }else{
                int yd=node.y-cur.y;
                if(yd>=-y_dis||yd<=y_dis) {
                    list.add(PlayerCache.getInstance().getPlayer(cur.key));
                }
            }
            cur=cur.xNext;
        }
        cur = node.xPrev;
        while(cur!=head){
            if(node.x-cur.x>x_dis) {
                break;
            }else{
                int yd=node.y-cur.y;
                if(yd>=-y_dis||yd<=y_dis) {
                    list.add(PlayerCache.getInstance().getPlayer(cur.key));
                }
            }
            cur=cur.xPrev;
        }
        return list;
    }
}